import axios from 'axios'
import { Message } from 'element-ui'
// import store from '@/store'
import { getToken } from '@/utils/auth'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 8000
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['token'] = getToken() // 让每个请求都携带token
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code === 200) {
      return response.data
    } else {
      Message({
        message: response.data.message || '操作异常',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    }
  },
  error => {
    console.log('axios : error')
    let code = 0
    try {
      code = error.response.status
    } catch (error) {
      console.log('')
    }
    let msg = ''
    if (code === 404) {
      msg = '操作失败，请求地址有误'
    } else if (code === 403) {
      msg = '操作失败，你没有该权限'
    } else {
      msg = '操作失败，未知错误'
    }
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
